package com.ch999.detect.View.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.FeatureInfo;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.hardware.camera2.CameraManager;
import android.location.LocationManager;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.ch999.View.MDProgressDialog;
import com.ch999.View.MDToolbar;
import com.ch999.commonUI.UITools;
import com.ch999.detect.AppBaseActivity;
import com.ch999.detect.R;
import com.ch999.detect.View.NewDetectView;
import com.ch999.detect.View.adapter.GoodsBjgzAdapter;
import com.ch999.detect.View.dialog.CustomSelectDialog;
import com.ch999.detect.View.dialog.MyCustomDialog;
import com.ch999.detect.View.dialog.NetTitleDialog;
import com.ch999.detect.View.dialog.NotCreat2CordDialog;
import com.ch999.detect.View.dialog.Show2CodeDialog;
import com.ch999.detect.mode.DetctControl;
import com.ch999.detect.mode.bean.DialogCustomMode;
import com.ch999.detect.mode.bean.GoodsBjgz;
import com.ch999.detect.presenter.NewDetectPresenter;
import com.ch999.detect.utils.DeviceUtils;
import com.ch999.detect.utils.TwoCadeUtils;
import com.github.mzule.activityrouter.annotation.Router;
import com.google.gson.Gson;
import com.jiuji.progressdashview.ProgressDashView;
import com.scorpio.mylib.Routers.MDRouters;
import com.scorpio.mylib.Tools.Logs;
import com.scorpio.mylib.Tools.Tools;
import com.scorpio.mylib.http.iface.DataResponse;
import com.scorpio.mylib.ottoBusProvider.BusEvent;
import com.scorpio.mylib.ottoBusProvider.BusProvider;
import com.squareup.otto.Subscribe;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.CALL_PHONE;

/**
 * 新的检测界面
 * Created by ch999android on 2017/12/26.
 */
@Router({"newDetect"})
public class NewDetectActivity extends AppBaseActivity implements NewDetectView, View.OnClickListener, SensorEventListener {
    private RecyclerView recyclerView;//检测项列表
    private ProgressDashView progressDashView;
    private TextView tv_bottom_again;//底部按钮

    private Context context;
    private GoodsBjgz bjgz;
    private GoodsBjgzAdapter bjgzAdapter;
    private MDToolbar mdToolbar;

    private MDProgressDialog dialog;

    private final static int HANDLER_STARTDETECT = 0X000010;//开始检测
    private final static int HANDLER_DETECTSUCCESS = 0X000011;//检测完成
    private final static int HANDLER_OPENDIALOG = 0X000012;//打开对话框
    private final static int HANDLER_CLOSRDIALOG = 0X000013;//关闭对话框
    private final static int HANDLER_COUNTDOWN = 0X000014;//
    private final static int HANDLER_SHOWTOAST = 0X000015;//显示toast
    private final static int HANDLER_SHOWANYDIALOG = 0X000016;//显示选择条目框

    public final static int BUSACTION_SCREENDETECT_SUCCESS = 0X000017;//屏幕检测完成
    public final static int BUSACTION_CAMERADETECT_SUCCESS = 0X000018;//摄像检测完成

    public final static int BUSACTION_ONTOUCH_SUCCESS = 0X000019;
    public final static int BUSACTION_CLOSE_ACTIVITY = 0X000020;

    //距离传感器实例
    private SensorManager mSensorManager;
    private Sensor mSensor;

    MyCustomDialog customDialog;
    private NetTitleDialog mNetTitleDialog;
    private Show2CodeDialog mShow2CodeDialog;


    private NewDetectPresenter mPresenter;
    public static int curIndex = 0;//当前检测项（list下标）

    private Thread detectThread;//自动检测线程

    private static Object lock = new Object();

    int po;//进度

    MyReceiver myReceiver;//广播接收器

    private CameraManager manager;// 声明CameraManager对象
    private Camera m_Camera = null;// 声明Camera对象

    private boolean isApp = true;//是否从主站跳转过来的。

    public static int chargeStatus;

    public boolean isAccount = true;
    /**
     * 检测完成
     */
    private boolean isDetectOver = false;
    private boolean isDetectCancel = false;//取消检测

    private NotCreat2CordDialog mNotCreat2CordDialog;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HANDLER_STARTDETECT:
                    //根据不同的检测项开始检测
                    Logs.Debug("test:开始检测" + curIndex + "-" + msg.obj.toString());
                    mPresenter.startDetecting((GoodsBjgz.AttrBean) msg.obj, isDetectOver);

                    break;
                case HANDLER_DETECTSUCCESS:
                    //单项检测完成，关闭dialog
                    Logs.Debug("test:检测成功" + curIndex + "-" + msg.arg1);
//                    int index = msg.arg1;//list下标
                    int flag = msg.arg1;//0-未检测（超时或者取消），其他-有检测结果关闭
                    if (mPresenter.isAccount()) {
                        if (flag == 0) {
                            isAccount = true;
                        } else {
                            isAccount = false;
                        }

                        mPresenter.setAccount(false);
                    }
                    bjgz.getAttr().get(curIndex).setItemPosation(flag);//替换已选择下标
                    bjgzAdapter.updateData(bjgz.getAttr());
//                    if (customDialog != null)
//                        customDialog.dismiss();

                    if (!isDetectOver) {
                        po = (int) (((double) (curIndex + 1f) / bjgz.getAttr().size()) * 360f);
                        progressDashView.setProgress(po);
                        //线程恢复
                        synchronized (lock) {
                            lock.notify();
                        }
                    }

                    if (curIndex == bjgz.getAttr().size() - 1) {
                        //最后一个，已完成
                        //    progressDashView.setProgress(100);
                        progressDashView.setProgress(360);
                        tv_bottom_again.setText("下一步");
                        isDetectOver = true;
                    }

                    break;
                case HANDLER_OPENDIALOG:
                    Logs.Debug("test:打开对话框" + curIndex);

                    try {
                        if (customDialog != null) {
                            DialogCustomMode customMode = (DialogCustomMode) msg.obj;

                            customDialog.show();
                            customDialog.setTvTitle(customMode.getTitle());
                            customDialog.setCustomView(customMode.getView());
                            customDialog.setIsShowButtom(customMode.isShowBottomBtn());
                            customDialog.setShowBtnOk(customMode.isShowBtnOk());
                            customDialog.setTvOkText(customMode.getOkText());
                            customDialog.setTvNoText(customMode.getNoText());
                            customDialog.setNeedCountDown(customMode.isNeedCountDown());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        // UITools.toastShowShort(context, "对话框打开失败");
                    }
                    break;
                case HANDLER_CLOSRDIALOG:
                    Logs.Debug("test:关闭对话框" + curIndex + "-" + msg.arg1);
                    if (customDialog != null) {
                        customDialog.dismiss();
                    }

                    int end = msg.arg1;//是否结束该项

                    if (end == 1) {
                        bjgz.getAttr().get(curIndex).setItemPosation(1);//替换已选择下标
                        bjgzAdapter.updateData(bjgz.getAttr());
                        if (!isDetectOver) {
                            po = (int) (((double) (curIndex + 1f) / bjgz.getAttr().size()) * 360f);
                            progressDashView.setProgress(po);
                            //线程恢复
                            synchronized (lock) {
                                lock.notify();
                            }

                        }

                        if (curIndex == bjgz.getAttr().size() - 1) {
                            //最后一个，已完成
                            tv_bottom_again.setText("下一步");
                            isDetectOver = true;
                        }
                    }
                    break;
                case HANDLER_COUNTDOWN:
                    //倒计时
//                    if (customDialog != null)
//                        customDialog.setCountDown(msg.arg1);
                    break;
                case HANDLER_SHOWTOAST:
                    UITools.toastShowShort(context, (String) msg.obj);
                    break;

                case HANDLER_SHOWANYDIALOG:

                    if (mCustomSelectDialog != null) {
                        GoodsBjgz.AttrBean attrBean = (GoodsBjgz.AttrBean) msg.obj;
                        try {
                            mCustomSelectDialog.show(attrBean.getValues(), attrBean.getTpname());
                            mCustomSelectDialog.setOnItemClickListener(new CustomSelectDialog.OnItemClickListener() {
                                @Override
                                public void onItemClick(GoodsBjgz.AttrBean.ValuesBean valuesBean, int position) {
//                        UITools.toastShowShort(context, valuesBean.getName() + "posation" + position);
                                    detectSuccess(position);
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                            UITools.toastShowShort(context, "对话框开启失败");
                        }
                    }
                    break;
            }

        }
    };
    private CustomSelectDialog mCustomSelectDialog;
    private DialogCustomMode mCustomMode;
    private boolean isPause;
    private String mApikey;


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        isApp = getIntent().getBooleanExtra("isAPP", true);
        mApikey = getIntent().getStringExtra("apikey");

        context = this;
        curIndex = 0;
        synchronized (lock) {
            lock.notify();
        }


        View inflate = LayoutInflater.from(context).inflate(R.layout.dialog_detect_call, null);

        //初始化距离传感器
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);


        Sensor defaultSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);

        mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
        boolean b = mSensorManager.registerListener(this, defaultSensor, SensorManager.SENSOR_DELAY_NORMAL);

        mCustomSelectDialog = new CustomSelectDialog(this);
        mCustomSelectDialog.setCancelable(false);

        BusProvider.getInstance().register(this);

        findViewById();
        setUp();
        if (!b) {
            mPresenter.setTLY(false);
        }

        customDialog = new MyCustomDialog(context, this, this, mPresenter);
        customDialog.setCancelable(false);
//        customDialog.create();


        mPresenter.setHandler(handler);
    }

    public void findViewById() {
        mdToolbar = (MDToolbar) this.findViewById(R.id.toolbar);
        recyclerView = (RecyclerView) findViewById(R.id.recyView);
        progressDashView = (ProgressDashView) findViewById(R.id.progress);
        tv_bottom_again = (TextView) findViewById(R.id.tv_bottom_again);

        tv_bottom_again.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isDetectOver) {
                    if (!Tools.checkoutPermissions(context, new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_PHONE_STATE})) {
                        new RxPermissions(NewDetectActivity.this).request(Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_PHONE_STATE)
                                .subscribe(new Action1<Boolean>() {
                                    @Override
                                    public void call(Boolean aBoolean) {
                                        if (aBoolean) {
                                            saveAttr(DeviceUtils.getIMEI(context), isApp);
                                        }
                                    }
                                });
                    } else {
                        saveAttr(DeviceUtils.getIMEI(context), isApp);
                    }
                } else {
                    //取消检测
                    if (isDetectCancel) {
                        //重新检测
                        //doDetect();
                        isDetectCancel = false;
                        tv_bottom_again.setText("检测中");
                    } else {
                        isDetectCancel = true;
                        tv_bottom_again.setText("检测中");
                    }
                }

            }
        });
    }

    public void setUp() {
        mdToolbar.setBackTitle("");
        mdToolbar.setRightTitle("");
        mdToolbar.setBackIcon(R.color.transparent);
        mdToolbar.setMainTitle("本机估价");
        mdToolbar.setOnMenuClickListener(new MDToolbar.OnMenuClickListener() {
            @Override
            public void onBackClick() {
                finish();
            }

            @Override
            public void onRigthClick() {

            }
        });


        mPresenter = new NewDetectPresenter(this, this);
        //检测项，从上个界面传入
        bjgz = (GoodsBjgz) getIntent().getSerializableExtra("bjgz");
        if (bjgz == null) {
            bjgz = new Gson().fromJson(Tools.getJsonForAssets(context, "bjgz.json"), GoodsBjgz.class);
//            finish();
        }

        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        recyclerView.setLayoutManager(layoutManager);
        bjgzAdapter = new GoodsBjgzAdapter(bjgz.getAttr(), context);
        recyclerView.setAdapter(bjgzAdapter);
        bjgzAdapter.setItemClickListner(new GoodsBjgzAdapter.ItemClickListner() {
            @Override
            public void onClick(int position) {
                if (position == -1 || !isDetectOver) {
                    return;
                }
                GoodsBjgz.AttrBean attrBean = bjgz.getAttr().get(position);
                curIndex = position;
                mPresenter.startDetecting(attrBean, isDetectOver);//单项检测
            }
        });


        //检测权限，必须有权限才能进行检测
        if (!Tools.checkoutPermissions(mContext, new String[]{
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA,
                Manifest.permission.ACCESS_WIFI_STATE,
                CALL_PHONE, ACCESS_COARSE_LOCATION
        })) {
            new RxPermissions(this).request(Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.CAMERA,
                    Manifest.permission.ACCESS_WIFI_STATE, CALL_PHONE,
                    ACCESS_COARSE_LOCATION)
                    .subscribe(new Action1<Boolean>() {
                        @Override
                        public void call(Boolean aBoolean) {
                            if (aBoolean) {
                                doDetect();
                            }
                        }
                    });
        } else {
            doDetect();
        }


        //注册广播监听器
        IntentFilter filter = new IntentFilter();
        filter.setPriority(2147483647);//优先级最高
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);//wifi状态变更
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);//充电状态变更
        filter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);//GPRS打开关或者关闭
        filter.addAction(LocationManager.MODE_CHANGED_ACTION);//GPRS打开关或者关闭
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//GPRS打开关或者关闭

        myReceiver = new MyReceiver();
        registerReceiver(myReceiver, filter);

    }

    boolean exit = false;

    private void doDetect() {

        detectThread = new Thread() {
            @Override
            public void run() {
                super.run();
                //循环检测，每一项

                for (int i = 0; i < bjgz.getAttr().size(); i++) {
                    if (isDetectOver || isDetectCancel) {
                        break;
                    }

                    if (exit) {
                        return;
                    }
                    GoodsBjgz.AttrBean attrBean = bjgz.getAttr().get(i);
                    curIndex = i;
//                    recyclerView.smoothScrollToPosition(curIndex);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            LinearLayoutManager mLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                            mLayoutManager.scrollToPositionWithOffset(curIndex, 0);
                        }
                    });

                    mPresenter.startDetecting(attrBean, isDetectOver);//单项检测
                    //等待本次任务结束
                    synchronized (lock) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        };
        detectThread.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //注销广播监听器
        customDialog.dismiss();
        unregisterReceiver(myReceiver);
        BusProvider.getInstance().unregister(this);
        mSensorManager.unregisterListener(this);
        curIndex = 0;
        exit = true;
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (mPresenter.isCallListener()) {
            //通话回调
            closeDialog(false);//关闭提示窗口
            showAnyDialog(bjgz.getAttr().get(curIndex));//弹出选择窗口
            mPresenter.setCallListener(false);//改变通话监听状态
        }
    }

    @Override
    public void onSucc(Object o) {

    }

    @Override
    public void onFail(String s) {

    }

    @Override
    public void onLoading() {

    }

    /**
     * 检测成功回调
     *
     * @param position 检测结果下标
     */
    @Override
    public void detectSuccess(int position) {

        sendMessage(HANDLER_DETECTSUCCESS, position, null);
    }

    /**
     * 统一发送handler消息
     *
     * @param what
     * @param arg1
     * @param obj
     */
    private void sendMessage(int what, int arg1, Object obj) {
        Message msg = new Message();
        msg.what = what;
        msg.arg1 = arg1;
        msg.obj = obj;
        handler.sendMessage(msg);
    }

    @Override
    public void onClick(View view) {
        int vid = view.getId();
        if (vid == R.id.tvOk) {
            //对话框确认按钮
            if ("扬声器".equals(bjgz.getAttr().get(curIndex).getTpname())) {

                //听到
                detectSuccess(0);
                closeDialog(false);
            }
        } else if (vid == R.id.llCancel) {
            //对话框取消按钮
            closeDialog(true);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isPause = true;
        mPresenter.setPause(true);

        if (mPresenter.isSeeting()) {
            subscripotion.unsubscribe();
        }
    }

    /**
     * 弹出窗口，并且倒计时
     *
     * @param customMode
     */
    @Override
    public void showDialog(DialogCustomMode customMode, boolean needCountDown) {
        startCountDown(customMode, needCountDown);
    }

    Subscription subscripotion;

    /**
     * 开启倒计时对话框
     */
    private void startCountDown(final DialogCustomMode customMode, boolean needCountDown) {
        mCustomMode = customMode;
        if (needCountDown) {
            final int count = 30;
            if (subscripotion != null && subscripotion.isUnsubscribed()) {
                subscripotion.unsubscribe();
            }

            Observer<Long> observer = new Observer<Long>() {
                @Override
                public void onCompleted() {
                    //倒计时结束
                    if (!mPresenter.isSeeting()) {
                        closeDialog(true);

                    }


                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                }

                @Override
                public void onNext(Long o) {

                    //倒计时
                    if (customDialog != null)
                        customDialog.setCountDown(o);
                }
            };

            subscripotion = Observable.interval(0, 1, TimeUnit.SECONDS)
                    .take(count + 1)
                    .map(new Func1<Long, Long>() {
                        @Override
                        public Long call(Long aLong) {
                            return count - aLong;
                        }
                    }).doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            sendMessage(HANDLER_OPENDIALOG, 0, customMode);
                        }
                    }).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
        } else {
            sendMessage(HANDLER_OPENDIALOG, 0, customMode);
        }
    }

    /**
     * 关闭自定义对话框
     *
     * @param isEndDetect true-结束检测项，进行下一项，false-至关闭当前对话框
     */
    @Override
    public void closeDialog(boolean isEndDetect) {
        sendMessage(HANDLER_CLOSRDIALOG, isEndDetect ? 1 : 0, null);
        if (subscripotion != null) {
            subscripotion.unsubscribe();
            mPresenter.CloseFingerprintIdentify();
        }

    }

    @Override
    public void showAnyDialog(final GoodsBjgz.AttrBean attrBean) {
        sendMessage(HANDLER_SHOWANYDIALOG, 0, attrBean);
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        float range = sensorEvent.values[0];
        if (sensorEvent.sensor.getType() == Sensor.TYPE_PROXIMITY) {

            if (range == mSensor.getMaximumRange()) {
                //Log.e("tag", "onSensorChanged: false");
            } else {
                if (mPresenter.isSenser()) {
                    mPresenter.setSenser(false);
                    detectSuccess(0);
                    closeDialog(false);
                }
            }
        } else if (sensorEvent.sensor.getType() == Sensor.TYPE_GYROSCOPE) {

            //   Log.e("tag", "事件：" + " x:" + sensorEvent.values[0] + " y:" + sensorEvent.values[1] + " z:" + sensorEvent.values[2]);

            float x1 = sensorEvent.values[0];
            float y1 = sensorEvent.values[1];
            float z1 = sensorEvent.values[2];

            if (x1 != 0 || y1 != 0 || z1 != 0) {
                if (mPresenter.isZNZCheck()) {
                    mPresenter.setZNZCheck(false);
                    detectSuccess(0);
                    closeDialog(false);
                }

                if (mPresenter.isTLYChekc()) {
                    mPresenter.setTLYChekc(false);
                    detectSuccess(0);
                    closeDialog(false);
                }
            }

        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * 系统广播接收器
     */
    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                //wifi状态改变广播
                case WifiManager.WIFI_STATE_CHANGED_ACTION:
                    int wifistats = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);

                    //监听到wifi已经打开，并且dialog是显示状态，避免其他状态下误监听
                    if (wifistats == WifiManager.WIFI_STATE_ENABLED && mPresenter.isWifiListener()) {
                        //关闭dialog并且检测wifi是否正常
                        closeDialog(false);
                        mPresenter.setWifiListener(false);
                        mPresenter.checkWifiGood();
                    }
                    break;
                //充电监听
                case Intent.ACTION_BATTERY_CHANGED:


                    chargeStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
                    Logs.Debug("充电广播接收：" + chargeStatus + "-charselistener:" + mPresenter.isChargeListener());

                    if (mPresenter.isChargeListener() && (chargeStatus == BatteryManager.BATTERY_STATUS_CHARGING || chargeStatus == BatteryManager.BATTERY_STATUS_FULL)) {
                        //正在充电或者电量满格
                        mPresenter.setChargeListener(false);
                        detectSuccess(0);//检测到成功
                        closeDialog(false);//由于上面已经调了success的方法了，这里就只是单独的关闭对话框
//                        mPresenter.checkWifiGood();
                    }
                    break;
                case LocationManager.PROVIDERS_CHANGED_ACTION:
                case LocationManager.MODE_CHANGED_ACTION:


                    boolean gpsEnable = DeviceUtils.isGPSEnable(context);
                    if (mPresenter.isGPSListener() && gpsEnable) {
                        mPresenter.setGPSListener(false);
                        detectSuccess(0);//坚持到成功
                        closeDialog(false);//由于上面已经调了success的方法了，这里就只是单独的关闭对话框
                    }

                    break;
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                            BluetoothAdapter.ERROR);
                    if (mPresenter.isBlotetooh() && state == BluetoothAdapter.STATE_ON) {
                        mPresenter.setBlotetooh(false);
                        detectSuccess(0);//坚持到成功
                        closeDialog(false);//由于上面已经调了success的方法了，这里就只是单独的关闭对话框
                    }

                    break;
            }
        }

    }


    @Override
    public void showNobottomDialog(DialogCustomMode customMode) {
        sendMessage(HANDLER_OPENDIALOG, 0, customMode);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mPresenter.isScreenView() && mPresenter.isClickScreen()) {
            closeDialog(false);
            showAnyDialog(bjgz.getAttr().get(curIndex));
            mPresenter.setScreenView(false);
        }

        if (mPresenter.isSeeting()) {
            mPresenter.checkFingerprint(mPresenter.mName, mPresenter.mView1);
//            showDialog(mCustomMode);
            mPresenter.setSeeting(false);

        }

        mPresenter.setPause(false);
    }

    @Subscribe
    public void onPostEvent(BusEvent postEvent) {
        int action = postEvent.getAction();
        if (action == BUSACTION_SCREENDETECT_SUCCESS) {
            //屏幕检测完成，此处弹出对话框有bug，移至onResume 做监听
//            closeDialog(false);
//            showAnyDialog(bjgz.getAttr().get(curIndex));
//            showToast("测试");
        } else if (action == BUSACTION_CAMERADETECT_SUCCESS) {
            //摄像功能检测完成
            detectSuccess(Integer.parseInt(postEvent.getContent()));
        } else if (action == BUSACTION_ONTOUCH_SUCCESS) {

            detectSuccess(Integer.parseInt(postEvent.getContent()));
            closeDialog(false);
        } else if (action == BUSACTION_CLOSE_ACTIVITY) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, 500);
        }
    }


    @Override
    public void openLinght() {

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            // your code using Camera API here - is between 1-20

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // your code using Camera2 API here - is api 21 or higher
            manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        }


        lightSwitch(false);

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                lightSwitch(true);
            }
        }, 500);
    }


    @SuppressLint("MissingPermission")
    public void setWifiEnabled(final boolean enabled) {
        @SuppressLint("WifiManagerLeak")
        WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (manager == null) return;
        if (enabled) {
            if (!manager.isWifiEnabled()) {
                manager.setWifiEnabled(true);
            }
        } else {
            if (manager.isWifiEnabled()) {
                manager.setWifiEnabled(false);
            }
        }
    }

    /**
     * 手电筒控制方法
     *
     * @param lightStatus
     * @return
     */
    private void lightSwitch(final boolean lightStatus) {
        if (lightStatus) { // 关闭手电筒
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                try {
                    manager.setTorchMode("0", false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                if (m_Camera != null) {
                    m_Camera.stopPreview();
                    m_Camera.release();
                    m_Camera = null;
                }
            }
        } else { // 打开手电筒
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                try {
                    manager.setTorchMode("0", true);
                    detectSuccess(0);
                } catch (Exception e) {
                    e.printStackTrace();
                    detectSuccess(1);
                }
            } else {
                try {
                    final PackageManager pm = getPackageManager();
                    final FeatureInfo[] features = pm.getSystemAvailableFeatures();
                    for (final FeatureInfo f : features) {
                        if (PackageManager.FEATURE_CAMERA_FLASH.equals(f.name)) { // 判断设备是否支持闪光灯
                            if (null == m_Camera) {
                                m_Camera = Camera.open();
                            }
                            final Camera.Parameters parameters = m_Camera.getParameters();
                            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                            m_Camera.setParameters(parameters);
                            m_Camera.startPreview();

//                        closeDialog(false);
                            detectSuccess(0);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    detectSuccess(1);
                }
            }
        }
    }


    /**
     * 判断Android系统版本是否 >= M(API23)
     */
    private boolean isM() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 提交数据
     *
     * @param mImei
     * @param isAPP
     */
    private void saveAttr(String mImei, final boolean isAPP) {

        if (!isAccount) {
            if (mNotCreat2CordDialog == null) {
                mNotCreat2CordDialog = new NotCreat2CordDialog(this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });

            }
            mNotCreat2CordDialog.show();
        } else {

            String paramsString = mPresenter.getParamsString(bjgz.getAttr());

            if (paramsString != null) {
                showLodingDialog();
                DetctControl.saveAttr(context, paramsString, mImei, isAPP, mApikey, new DataResponse() {
                    @Override
                    public void onSucc(final Object response) {
                        hideLodingDialog();
                        if (isAPP) {
                            new MDRouters.Builder().build((String) response).create(context).go();
                        } else {
                            Intent intent = new Intent(context, DetectWebView.class);
                            intent.putExtra("isApp", isAPP);
                            intent.putExtra("apikey", mApikey);
                            intent.putExtra(DetectWebView.URL, response.toString());
                            startActivity(intent);
                            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                        }
                        //finish();
//                    if (isAPP) {
////                    if (false) {
//                        new MDRouters.Builder().build((String) response).create(context).go();
//                        finish();
//                    } else {
//                        show2Card(response);
//                    }
                    }

                    @Override
                    public void onFail(String error) {
                        hideLodingDialog();

                        showNetConnetDialog(error);
                    }
                });
            }
        }


    }

    public void showLodingDialog() {
        if (dialog == null) {
            dialog = new MDProgressDialog(context);
        }
        try {
            dialog.show();
        } catch (Exception e) {

        }

    }


    protected void hideLodingDialog() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_newdetect;
    }

    @Override
    public void initView(Bundle savedInstanceState) {

    }

    @Override
    public void findView() {

    }

    /**
     * 显示内有网络
     */
    private void showNetConnetDialog(String msg) {
        if (mNetTitleDialog == null) {

            mNetTitleDialog = new NetTitleDialog(context, new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
        }
        mNetTitleDialog.show(msg);

    }


    /**
     * 显示二维码
     *
     * @param response
     */
    private void show2Card(final Object response) {
        final String filePath = TwoCadeUtils.getFileRoot(NewDetectActivity.this) + File.separator + "qr_" + System.currentTimeMillis() + ".jpg";

        new Thread(new Runnable() {
            @Override
            public void run() {

                boolean success = TwoCadeUtils.createQRImage(response.toString() + "&DeviceId=1", 800, 800, null, filePath);
                if (success) {


                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            hideLodingDialog();
                            if (mShow2CodeDialog == null) {
                                mShow2CodeDialog = new Show2CodeDialog(context);
                            }

                            mShow2CodeDialog.showDialog(filePath);

                        }
                    });

                } else {
                    Toast.makeText(context, "生成失败", Toast.LENGTH_SHORT).toString();
                }
            }

        }).start();
    }

    @Override
    public void showToast(String text) {
        sendMessage(HANDLER_SHOWTOAST, 0, text);
    }
}
